package com.cxf.windex.rest;

import com.cxf.windex.base.bean.LockInfo;
import com.cxf.windex.base.constant.LockConstant;
import com.cxf.windex.base.constant.UserConstant;
import com.cxf.windex.base.msg.ObjectRestResponse;
import com.cxf.windex.base.rest.BaseRestController;
import com.cxf.windex.biz.CxfAccountBiz;
import com.cxf.windex.biz.CxfAccountLogBiz;
import com.cxf.windex.biz.CxfUserBiz;
import com.cxf.windex.entity.CxfAccount;
import com.cxf.windex.entity.CxfAccountLog;
import com.cxf.windex.entity.CxfUser;
import com.cxf.windex.enums.OperateEnum;
import com.cxf.windex.task.PayTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.math.BigDecimal;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @program: drp
 * @description: 资金概况
 * @author: chenxf
 * @create: 2018-05-24 16:13
 **/
@Api(tags = {"聚能小宝 - 钱包接口"})
@Controller
@RequestMapping("api_account")
public class CxfAccountController extends BaseRestController<CxfAccountBiz, CxfAccount> {

    @Autowired
    private CxfUserBiz cxfUserBiz;
    @Autowired
    private CxfAccountLogBiz cxfAccountLogBiz;
    @Autowired
    private PayTask payTask;

    @ApiOperation(value="获取钱包", notes="获取钱包信息")
    @RequestMapping(value = "/money", method = RequestMethod.POST)
    @ResponseBody
    public ObjectRestResponse money(){
        String userId = this.getCurrentUserId();
        if(userId==null|| StringUtils.isBlank(userId)){
            return new ObjectRestResponse().rel(false).msg("用户未登陆");
        }
        CxfAccount queryEntity = new CxfAccount();
        queryEntity.setUserid(userId);

        CxfAccount money = baseBiz.selectOne(queryEntity);
        if (money == null) {
            return new ObjectRestResponse().rel(false).msg("用户资金信息查询失败");
        }
        return new ObjectRestResponse().rel(true).msg("查询成功").result(money);
    }

    @ApiOperation(value = "提现", notes = "提现")
    @RequestMapping(value = "/tx", method = RequestMethod.POST)
    @ResponseBody
    public ObjectRestResponse tx(@RequestParam Map<String, String> map) {
        String userId = this.getCurrentUserId();
        if (userId == null || StringUtils.isBlank(userId)) {
            return new ObjectRestResponse().rel(false).msg("用户未登陆");
        }
        if (StringUtils.isBlank(map.get("zcCount"))) {
            return new ObjectRestResponse().rel(false).msg("提现金额不能为空");
        }

        CxfAccount queryEntity = new CxfAccount();
        queryEntity.setUserid(userId);

        //账号转入
        LockInfo lockInfo = new LockInfo(LockConstant.USER_LOCK + userId);
        try {
            CxfAccount money = baseBiz.selectOne(queryEntity);
            if (money == null) {
                lockInfo.unlock();
                return new ObjectRestResponse().rel(false).msg("用户资金信息查询失败");
            }

            if (money.getBalance().compareTo(new BigDecimal(map.get("zcCount"))) < 0) {
                lockInfo.unlock();
                return new ObjectRestResponse().rel(false).msg("可用余额:" + money.getBalance() + " 不足");
            }
            money.setBalance(money.getBalance().subtract(new BigDecimal(map.get("zcCount"))));
            money.setFrozen(money.getFrozen().add(new BigDecimal(map.get("zcCount"))));

            payTask.doAccount(money, OperateEnum.TXFROZE, map.get("zcCount"), String.format(UserConstant.TX_FROZE_MSG, map.get("zcCount")));
        } catch (Exception e) {
            logger.error(" e={}", e.getMessage());
        } finally {
            lockInfo.unlock();
        }
        return new ObjectRestResponse().rel(true).msg("提现成功");
    }

    @ApiOperation(value = "提现成功", notes = "提现成功")
    @RequestMapping(value = "/txsuc", method = RequestMethod.POST)
    @ResponseBody
    public ObjectRestResponse txsuc(@RequestParam Map<String, String> map) {

        if (StringUtils.isBlank(map.get("zcCount"))) {
            return new ObjectRestResponse().rel(false).msg("提现金额不能为空");
        }
        if (StringUtils.isBlank(map.get("id"))) {
            return new ObjectRestResponse().rel(false).msg("提现ID不能为空");
        }

        CxfAccountLog cxfAccountLog = cxfAccountLogBiz.selectById(Long.parseLong(map.get("id")));

        String userId = cxfAccountLog.getUserid();
        CxfAccount queryEntity = new CxfAccount();
        queryEntity.setUserid(userId);
        //账号转入
        LockInfo lockInfo = new LockInfo(LockConstant.USER_LOCK + userId);
        try {

            CxfAccount money = baseBiz.selectOne(queryEntity);
            if (money == null) {
                lockInfo.unlock();
                return new ObjectRestResponse().rel(false).msg("用户资金信息查询失败");
            }
            if (money.getFrozen().compareTo(new BigDecimal(map.get("zcCount"))) < 0) {
                lockInfo.unlock();
                return new ObjectRestResponse().rel(false).msg("冻结余额:" + money.getFrozen() + " 不足");
            }
            //减掉总金额 和冻结金额
            money.setAccount(money.getAccount().subtract(new BigDecimal(map.get("zcCount"))));
            money.setFrozen(money.getFrozen().subtract(new BigDecimal(map.get("zcCount"))));

            payTask.doAccount(money, OperateEnum.TXSUCCESS, map.get("zcCount"), String.format(UserConstant.TX_SUCCESS_MSG, map.get("zcCount")));


            if (StringUtils.isNotBlank(map.get("fee")) && !map.get("fee").equals("0")) {
                if (money.getFrozen().compareTo(new BigDecimal(map.get("fee"))) < 0) {
                    lockInfo.unlock();
                    return new ObjectRestResponse().rel(false).msg("冻结余额:" + money.getFrozen() + " 不足");
                }
                //减掉总金额 和冻结金额
                money.setAccount(money.getAccount().subtract(new BigDecimal(map.get("fee"))));
                money.setFrozen(money.getFrozen().subtract(new BigDecimal(map.get("fee"))));
                money.setFee(money.getFee().add(new BigDecimal(map.get("fee"))));
                payTask.doAccount(money, OperateEnum.TXFEE, map.get("fee"), String.format(UserConstant.TX_FEE_MSG, map.get("fee")));

            }

        } catch (Exception e) {
            logger.error(" e={}", e.getMessage());
        } finally {
            lockInfo.unlock();
        }

        //设置提现为已处理
        cxfAccountLog.setStatus("1");
        cxfAccountLogBiz.updateSelectiveById(cxfAccountLog);
        return new ObjectRestResponse().rel(true).msg("提现成功");
    }

    @ApiOperation(value = "奖励", notes = "奖励")
    @RequestMapping(value = "/bonus", method = RequestMethod.POST)
    @ResponseBody
    public ObjectRestResponse bonus(@RequestParam Map<String, String> map) {

        if (StringUtils.isBlank(map.get("zcCount"))) {
            return new ObjectRestResponse().rel(false).msg("奖励金额不能为空");
        }
        if (StringUtils.isBlank(map.get("phone"))) {
            return new ObjectRestResponse().rel(false).msg("奖励用户不能为空");
        }
        CxfUser cxfUser = new CxfUser();
        cxfUser.setUsername(map.get("phone"));
        cxfUser=cxfUserBiz.selectOne(cxfUser);
        if(cxfUser==null){
            return new ObjectRestResponse().rel(false).msg("奖励用户不存在");
        }

        String userId = cxfUser.getId();
        CxfAccount queryEntity = new CxfAccount();
        queryEntity.setUserid(userId);
        //账号转入
        LockInfo lockInfo = new LockInfo(LockConstant.USER_LOCK + userId);
        try {

            CxfAccount money = baseBiz.selectOne(queryEntity);
            if (money == null) {
                lockInfo.unlock();
                return new ObjectRestResponse().rel(false).msg("用户资金信息查询失败");
            }

            //总金额 余额 奖金增加
            money.setAccount(money.getAccount().add(new BigDecimal(map.get("zcCount"))));
            money.setBalance(money.getBalance().add(new BigDecimal(map.get("zcCount"))));
            money.setBonus(money.getBonus().add(new BigDecimal(map.get("zcCount"))));

            payTask.doAccount(money, OperateEnum.BONUS, map.get("zcCount"), map.get("notes"));


            if (StringUtils.isNotBlank(map.get("fee")) && !map.get("fee").equals("0")) {

                //总金额 余额 奖金减少
                money.setAccount(money.getAccount().subtract(new BigDecimal(map.get("fee"))));
                money.setBalance(money.getBalance().subtract(new BigDecimal(map.get("fee"))));
                money.setBonus(money.getBonus().subtract(new BigDecimal(map.get("fee"))));

                payTask.doAccount(money, OperateEnum.BONUSFEE, map.get("fee"),map.get("notes"));

            }

        } catch (Exception e) {
            logger.error(" e={}", e.getMessage());
        } finally {
            lockInfo.unlock();
        }

        return new ObjectRestResponse().rel(true).msg("奖励发放成功");
    }

    @ApiOperation(value = "提现失败", notes = "提现失败")
    @RequestMapping(value = "/txfail", method = RequestMethod.POST)
    @ResponseBody
    public ObjectRestResponse txfail(@RequestParam Map<String, String> map) {


        if (StringUtils.isBlank(map.get("id"))) {
            return new ObjectRestResponse().rel(false).msg("提现ID不能为空");
        }

        CxfAccountLog cxfAccountLog = cxfAccountLogBiz.selectById(Long.parseLong(map.get("id")));

        String userId = cxfAccountLog.getUserid();
        CxfAccount queryEntity = new CxfAccount();
        queryEntity.setUserid(userId);
        //账号转入
        LockInfo lockInfo = new LockInfo(LockConstant.USER_LOCK + userId);
        try {

            CxfAccount money = baseBiz.selectOne(queryEntity);
            if (money == null) {
                lockInfo.unlock();
                return new ObjectRestResponse().rel(false).msg("用户资金信息查询失败");
            }
            if (money.getFrozen().compareTo(cxfAccountLog.getMoney()) < 0) {
                lockInfo.unlock();
                return new ObjectRestResponse().rel(false).msg("冻结余额:" + money.getFrozen() + " 不足");
            }
            //余额增加 和冻结金额减少
            money.setBalance(money.getBalance().add(cxfAccountLog.getMoney()));
            money.setFrozen(money.getFrozen().subtract(cxfAccountLog.getMoney()));

            payTask.doAccount(money, OperateEnum.TXFAIL, cxfAccountLog.getMoney().toString(), map.get("notes"));


        } catch (Exception e) {
            logger.error(" e={}", e.getMessage());
        } finally {
            lockInfo.unlock();
        }

        //设置提现为已处理
        cxfAccountLog.setStatus("1");
        cxfAccountLogBiz.updateSelectiveById(cxfAccountLog);
        return new ObjectRestResponse().rel(true).msg("提现失败");
    }
}
